package com.xky.ui.module.customersManagement;

import com.xky.pojo.Customers;
import com.xky.ui.main.MainView;
import com.xky.ui.module.customersManagement.select.SelectCustomers;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.util.List;
import java.util.concurrent.ExecutionException;

/**
 * 客户信息管理类
 * 负责显示和刷新客户信息
 */
public class CustomersInfo {
    private static JTable customersTable;
    private static final String MODULE_NAME = "客户信息";

    /**
     * 显示客户信息页面
     */
    public static void showCustomersPage() {
        try {
            // 创建客户信息面板
            JPanel customersInfoPanel = CustomersMassage.createCustomersPanel(CustomersInfo::refreshCustomersData);

            // 获取表格组件
            initializeTable(customersInfoPanel);

            // 更新右侧面板
            updateMainPanel(customersInfoPanel);
            
            // 立即刷新一次
            refreshCustomersData();
            
            // 更新状态消息
            MainView.updateStatusMessage(MODULE_NAME + "页面已加载");
        } catch (Exception e) {
            handleException(e, "加载" + MODULE_NAME + "页面失败");
        }
    }
    
    /**
     * 初始化表格组件
     * @param panel 包含表格的面板
     * @throws IllegalStateException 如果无法找到表格组件
     */
    private static void initializeTable(JPanel panel) throws IllegalStateException {
        // 尝试通过索引获取JScrollPane
        try {
            if (panel.getComponentCount() >= 5) {
                Component comp = panel.getComponent(4);
                if (comp instanceof JScrollPane) {
                    JScrollPane scrollPane = (JScrollPane) comp;
                    Component viewComponent = scrollPane.getViewport().getView();
                    if (viewComponent instanceof JTable) {
                        customersTable = (JTable) viewComponent;
                        return;
                    }
                }
            }
            
            // 如果上面的方法失败，尝试遍历所有组件查找表格
            for (Component comp : panel.getComponents()) {
                if (comp instanceof JScrollPane) {
                    JScrollPane scrollPane = (JScrollPane) comp;
                    Component viewComponent = scrollPane.getViewport().getView();
                    if (viewComponent instanceof JTable) {
                        customersTable = (JTable) viewComponent;
                        return;
                    }
                }
            }
            
            throw new IllegalStateException("无法找到表格组件");
        } catch (Exception e) {
            throw new IllegalStateException("初始化表格失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 更新主面板
     * @param panel 要显示的面板
     */
    private static void updateMainPanel(JPanel panel) {
        MainView.rightPanel.removeAll();
        MainView.rightPanel.add(panel, BorderLayout.CENTER);
        MainView.rightPanel.revalidate();
        MainView.rightPanel.repaint();
        
        // 注册刷新操作
        MainView.registerRefreshAction(MODULE_NAME, CustomersInfo::refreshCustomersData);
    }

    /**
     * 刷新客户数据
     */
    static void refreshCustomersData() {
        // 显示加载指示器
        MainView.updateStatusMessage("正在加载" + MODULE_NAME + "数据...");
        
        new SwingWorker<List<Customers>, Void>() {
            @Override
            protected List<Customers> doInBackground() {
                validateTable();
                
                DefaultTableModel model = (DefaultTableModel) customersTable.getModel();
                model.setRowCount(0);

                // 获取所有客户数据
                return SelectCustomers.selectAllCustomers();
            }

            @Override
            protected void done() {
                try {
                    List<Customers> customersList = get();
                    if (customersTable != null) {
                        CustomersMassage.updateTableData(customersTable, customersList);
                        MainView.rightPanel.repaint();
                        MainView.updateStatusMessage("已加载 " + customersList.size() + " 条" + MODULE_NAME + "数据");
                    }
                } catch (InterruptedException | ExecutionException e) {
                    handleException(e, "刷新失败");
                }
            }
        }.execute();
    }
    
    /**
     * 验证表格是否已初始化
     * @throws IllegalStateException 如果表格未初始化
     */
    private static void validateTable() throws IllegalStateException {
        if (customersTable == null) {
            throw new IllegalStateException("表格未初始化");
        }
    }
    
    /**
     * 处理异常
     * @param e 异常
     * @param message 错误消息前缀
     */
    private static void handleException(Exception e, String message) {
        e.printStackTrace();
        JOptionPane.showMessageDialog(null, 
            message + ": " + e.getMessage(), 
            "错误", JOptionPane.ERROR_MESSAGE);
        MainView.updateStatusMessage(MODULE_NAME + "数据加载失败");
    }
}
